package com.hsxshop.util;

import com.hsxshop.model.ManagerUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;

/**
 * Created by wangchongya on 17/7/19.
 */
public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //创建session
        HttpSession session =request.getSession();

        //无需登录，允许访问的地址
        String[] allowUrls =new String[]{"/html/index.html","/login/do"};
        //获取请求地址
        String url =request.getRequestURL().toString();

        //获得session中的用户
        ManagerUser user =(ManagerUser) session.getAttribute("userToken");

        for (String strUrl : allowUrls) {
            if(url.contains(strUrl))
            {
                return true;
            }
        }

        if(user ==null)
        {
            String outContent=JsonTool.return401Error();
            OutputStream os= response.getOutputStream();
            os.write(outContent.getBytes());
            os.flush();
            os.close();
            return false;
        }

        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
